package io.rocketman.common.thread;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author He Peng
 * @create 2018-05-27 4:07
 * @update 2018-05-27 4:07
 * @updatedesc : 更新说明
 * @see
 */
public class NamedThreadFactory implements ThreadFactory {

    private static final AtomicInteger THREAD_COUNTER = new AtomicInteger(1);
    private final String threadNamePrefix;
    private final Boolean daemon;
    private final ThreadGroup threadGroup;

    public NamedThreadFactory(String threadNamePrefix) {
        this(threadNamePrefix , true);
    }

    public NamedThreadFactory(String threadNamePrefix , boolean daemon) {
        this.threadNamePrefix = threadNamePrefix + "-thread-";
        this.daemon = daemon;
        SecurityManager securityManager = System.getSecurityManager();
        this.threadGroup = securityManager != null ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup();
    }

    @Override
    public Thread newThread(Runnable r) {
        String tName = this.threadNamePrefix + THREAD_COUNTER.getAndIncrement();
        Thread thread = new Thread(this.threadGroup, r, tName);
        thread.setDaemon(this.daemon);
        return thread;
    }

    public ThreadGroup getThreadGroup() {
        return threadGroup;
    }
}
